/**
 * @开发版权 云南赢中吉洋智能技术有限公司（YNYZGY）
 * @项目名称 昆明长水机场三维视频融合系统(AVF3D)
 * @版本信息 v1.0
 * @开发人员 zhous
 * @开发日期 2021-03-22
 * @修订日期
 * @描述  GlobalActionInterceptor 
 */
package com.jzg.common.interceptor;

import java.sql.SQLException;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jzg.common.plugins.shiro.IncorrectCaptchaException;
import com.jzg.common.render.RenderBean;

public class GlobalActionInterceptor implements Interceptor {

	public void intercept(Invocation inv) {
		try {
			Controller controller = inv.getController();
			controller.getResponse().setHeader("Access-Control-Allow-Origin", "*");
			controller.getResponse().setHeader("Access-Control-Allow-Methods", "POST, GET");
			controller.getResponse().setHeader("Access-Control-Max-Age", "3600");
			controller.getResponse().setHeader("Access-Control-Allow-Headers","Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
			inv.invoke();
		} catch (Exception e) {
			RenderBean renderBean = new RenderBean();
			if (e instanceof AuthenticationException) {
				renderBean.setCode(500);
				renderBean.setMessage("该用户不存在或密码错误!");
			} else if (e instanceof UnauthenticatedException) {
				renderBean.setCode(401);
				renderBean.setMessage("登录过期!");
			} else if (e instanceof BindException) {
				renderBean.setCode(400);
				renderBean.setMessage("参数有误!");
			} else if (e instanceof HttpRequestMethodNotSupportedException) {
				renderBean.setCode(405);
				renderBean.setMessage("不允许的方法!");
			} else if (e instanceof SQLException) {
				renderBean.setCode(500);
				renderBean.setMessage(e.getMessage());
			} else if (e instanceof ActiveRecordException) {
				renderBean.setCode(500);
				renderBean.setMessage(e.getMessage());
			} else if (e instanceof IncorrectCaptchaException) {
				renderBean.setCode(500);
				renderBean.setMessage("验证码错误!");
			} else if (e instanceof UnknownAccountException) {
				renderBean.setCode(500);
				renderBean.setMessage("用户名或密码错误!");
			} else if (e instanceof IncorrectCredentialsException) {
				renderBean.setCode(500);
				renderBean.setMessage("用户名或密码错误!");
			} else {
				renderBean.setCode(500);
				renderBean.setMessage(e.getMessage());
			}
			e.printStackTrace();
			inv.getController().renderJson(renderBean);
		}
	}
	
}
